package cn.iocoder.yudao.module.jky.service.order;

import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jky.controller.admin.order.vo.OrderCreateReqVO;
import cn.iocoder.yudao.module.jky.controller.admin.order.vo.OrderExportReqVO;
import cn.iocoder.yudao.module.jky.controller.admin.order.vo.OrderPageReqVO;
import cn.iocoder.yudao.module.jky.controller.admin.order.vo.OrderUpdateReqVO;
import cn.iocoder.yudao.module.jky.convert.order.OrderConvert;
import cn.iocoder.yudao.module.jky.convert.orderdetail.OrderDetailConvert;
import cn.iocoder.yudao.module.jky.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.jky.dal.dataobject.orderdetail.OrderDetailDO;
import cn.iocoder.yudao.module.jky.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.jky.dal.mysql.orderdetail.OrderDetailMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.jky.enums.ErrorCodeConstants.ORDER_NOT_EXISTS;

/**
 * 订单 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@DS("slave")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private DeptApi deptApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private PermissionApi permissionApi;

    @Override
    public Integer createOrder(OrderCreateReqVO createReqVO) {
        // 插入
        OrderDO order = OrderConvert.INSTANCE.convert(createReqVO);
        orderMapper.insert(order);
        // 返回
        return order.getId();
    }

    @Override
    public void updateOrder(OrderUpdateReqVO updateReqVO) {
        // 校验存在
        validateOrderExists(updateReqVO.getId());
        // 更新
        OrderDO updateObj = OrderConvert.INSTANCE.convert(updateReqVO);
        orderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrder(Integer id) {
        // 校验存在
        validateOrderExists(id);
        // 删除
        orderMapper.deleteById(id);
    }

    private void validateOrderExists(Integer id) {
        if (orderMapper.selectById(id) == null) {
            throw exception(ORDER_NOT_EXISTS);
        }
    }

    @Override
    public OrderDO getOrder(Integer id) {
        OrderDO orderDO = orderMapper.selectById(id);
        List<OrderDetailDO> orderDetailDOS = orderDetailMapper.selectList(new LambdaQueryWrapperX<OrderDetailDO>().eq(OrderDetailDO::getOrderId, id));
        orderDO.setOrderDetailDOList(OrderDetailConvert.INSTANCE.convertList(orderDetailDOS));
        return orderDO;
    }

    @Override
    public List<OrderDO> getOrderList(Collection<Integer> ids) {
        return orderMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<OrderDO> getOrderPage(OrderPageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;

        PageResult<OrderDO> goodsDOPageResult = null;
        // 如果是供应商管理员角色,获取供应商租户的所有供应商的订单

        // 供应商用户只能获取它自己的订单
        CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(loginUser.getId());
        if (Objects.nonNull(user.getData())) {
            CommonResult<Boolean> supplier = permissionApi.hasAnyRoles(loginUser.getId(), "supplier");
            if (supplier.getData()) {
                pageReqVO.setSupplierId(user.getData().getDeptId().intValue());
            }
        }


        PageResult<OrderDO> orderDOPageResult = orderMapper.selectPage(pageReqVO);
        orderDOPageResult.getList().forEach(item -> {
            if (item.getSupplierId() != 0) {
                long id = Long.parseLong(String.valueOf(item.getSupplierId()));
                item.setSupplierName(deptApi.getDept(id).getData().getName());
            }
        });

        return orderDOPageResult;
    }

    @Override
    public PageResult<OrderDO> getOrderCheckingPage(OrderPageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;

        // 如果是供应商管理员角色,获取供应商租户的所有供应商的订单

        // 对账订单必须是状态为2,3,4,5的
        pageReqVO.setCheckingStatus(ListUtil.of(2,3,4,5));
        PageResult<OrderDO> orderDOPageResult = orderMapper.selectPage(pageReqVO);
        orderDOPageResult.getList().forEach(item -> {
            if (item.getSupplierId() != 0) {
                long id = Long.parseLong(String.valueOf(item.getSupplierId()));
                item.setSupplierName(deptApi.getDept(id).getData().getName());
            }
        });

        return orderDOPageResult;
    }


    @Override
    public List<OrderDO> getOrderList(OrderExportReqVO exportReqVO) {
        return orderMapper.selectList(exportReqVO);
    }

}
